const net = require('net');

const tcp_events_map = {
    data: "data",
    close: "close",
    error: "error",
    disconnect: "end"
};

/******* 
 * @description: 监听TCP事件
 * @param {Integer} fd
 * @param {Function} event data / close / error / disconnect
 * @return {*}
 * @author: null
 */
function on(fd, __id__, event) {
    if (fd >= globalThis.tcpClient.clients.length) {
        throw new Error("client index is invaild");
    }

    const client = globalThis.tcpClient.clients[fd];
    if (!client) throw new Error("http client not exists");

    if (!Object.keys(tcp_events_map).includes(event)) return;

    client.on(tcp_events_map[event], function(res) {
        globalThis.eventbus.emit(__id__, event, [res]);
    });
}

/******* 
 * @description: 向服务器发送数据
 * @param {Integer} fd
 * @param {String | Buffer} data
 * @param {Integer} size 实际上没用到这个值
 * @return {*}
 * @author: null
 */
function send(fd, data, size) {
    if (fd >= globalThis.tcpClient.clients.length) throw new Error("client index is invaild");
    const client = globalThis.tcpClient.clients[fd];
    if (!client) throw new Error("http client not exists");
    client.write(data);
    console.log(`[TCP] ===> write, size: ${size}`);
}

/******* 
 * @description: 关闭客户端
 * @param {Integer} fd
 * @return {*}
 * @author: null
 */
function close(fd) {
    // 判断fd是否超过globalThis.tcpClient.clients的长度
    if (fd >= globalThis.tcpClient.clients.length) throw new Error("client index is invaild");
    const client = globalThis.tcpClient.clients[fd];
    if (client) client.end();
    // 删除globalThis缓存的对象
    globalThis.tcpClient.clients.splice(fd, 1);
}

/******* 
 * @description: 连接服务端
 * @param {String | Buffer} host 
 * @param {Integer} size 实际上用不到这个值
 * @param {Integer} port 
 * @return {*}
 * @author: null
 */
function connect(host, size, port) {
    if (Buffer.isBuffer(host)) {
        host = host.toString("utf8");
        console.log(`[TCP] ===> connect, host: ${host}, size: ${size}, post: ${port}`);
    }

    const client = net.createConnection({ host: host, port: port }, function() {
        console.log('[TCP] ===> connected to server!');
    });

    // client.on("data", function(res) {
    //     console.log(res);
    // });

    // 监听事件
    client.on('timeout', function(res) {
        console.log(res);
        console.log('[TCP] ===> socket timeout');
        client.end();
    });

    client.on('error', function(err) {
        // 如果出现以下错误，请检查你的电脑是否开启了代理软件
        // {"errno":-4077,"code":"ECONNRESET","syscall":"read"}
        // https://stackoverflow.com/questions/63992562/econnreset-error-in-nodejs-while-calling-api-request
        console.log(err);
        console.log('[TCP] ===> socket error');
        client.end();
    });

    // client.on('close', function() {
    //     console.log('close from server');
    // });

    // client.on('end', function() {
    //     console.log('disconnected from server');
    // });

    if (globalThis.tcpClient == undefined || !globalThis.tcpClient) {
        globalThis.tcpClient = {
            index: 0,
            clients: []
        }
    }
    
    globalThis.tcpClient.clients.push(client);
    return globalThis.tcpClient.index++;
}

if (globalThis.platform == "nodejs") {
    module.exports = {
        on: on,
        send: send,
        close: close,
        connect: connect,
    };
}
